#!/bin/bash
# -*- sh -*-
# Support functions for shell munin plugins
#

clean_fieldname () {
    # Clean up field name so it complies with munin requirements.
    #
    # usage: name="$(clean_fieldname "$item")"
    #
    echo "$@" | sed -e 's/^[^A-Za-z_]/_/' -e 's/[^A-Za-z0-9_]/_/g' -e 's/^.*\([A-Za-z0-9_]\{19\}\)$/\1/'
}

# Look up warning environment variables in the following order:
# $1 = field name
# $2 = optional override of environment variable name
#
# Hmm, this first looks for field_warning, then $2 then warning.  Not the
# order one expects.
#
get_warning () {
    warn_env="${1}_warning"
    defwarn_env=${2:-warning}
    # eval export spam=\$${field}_warning
    warntmp=$(eval "echo \$${warn_env}")
    warntmpd=$(eval "echo \$${defwarn_env}")

    warnout=${warntmp:-$warntmpd}

    if [ -n "${warnout}" ]; then
        echo "${warnout}"
    fi
}


print_warning () {
        warnout=$(get_warning $1 $2)
        if [ -n "${warnout}" ]; then
                echo "${1}.warning ${warnout}"
        fi
}

# Ditto for critical values
#
get_critical () {
        crit_env="${1}_critical"
        defcrit_env=${2:-critical}
        crittmp=$(eval "echo \$${crit_env}")
        crittmpd=$(eval "echo \$${defcrit_env}")

        critout=${crittmp:-$crittmpd}

        if [ -n "${critout}" ]; then
                echo "${critout}"
        fi
}

print_critical () {
        critout=$(get_critical $1 $2)
        if [ -n "${critout}" ]; then
                echo "${1}.critical ${critout}"
        fi
}

# janl_: can I in a shell script save STDOUT so I can restore it after
#        a "exec >>somefile"?
# james: exec 2>&4 etc.
# janl_: this saves handle 2 in handle 4?
# james: yes, that's basically the same as dup
# james: dup2, even
# janl_: so... ... "exec 4>&2" to restore?
# james: Actually you can do: exec 4>&2- ... which closes 4 afterwards ...
#        I think that's historical behaviour and not a newish extension

